package hu.issue.framework.web.servlet;

import java.io.File;
import java.io.FilenameFilter;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;

class PackageLoader {
	private final String javaPackage;

	public PackageLoader(final String javaPackage) {
		this.javaPackage = javaPackage;
	}

	public List<Class<?>> loadClasses() throws URISyntaxException, ClassNotFoundException {
		final List<Class<?>> classes = new LinkedList<Class<?>>();

		final File packageDirectory = getPackageDirectory(this.javaPackage);
		final File[] classFiles = packageDirectory.listFiles(new ControllerClassFilter());
		for (final File classFile : classFiles) {
			final Class<?> clazz = loadClass(classFile);
			classes.add(clazz);
		}

		return classes;

	}

	private File getPackageDirectory(final String javaPackage) throws URISyntaxException {
		final String packageResource = "/" + javaPackage.replace('.', File.separatorChar);
		final URL url = getClass().getClassLoader().getResource(packageResource);
		return new File(url.toURI());
	}

	private Class<?> loadClass(final File controllerFile) throws URISyntaxException, ClassNotFoundException {
		final String path = "WEB-INF/classes";
		String controllerFileName = controllerFile.getAbsolutePath();
		controllerFileName = controllerFileName.replaceAll("\\.class", "");
		final int index = controllerFileName.indexOf(path) + path.length() + 1;
		final String className = controllerFileName.substring(index).replace(File.separatorChar, '.');
		return Class.forName(className);
	}

	private static class ControllerClassFilter implements FilenameFilter {

		@Override
		public boolean accept(final File dir, final String name) {
			return name.endsWith("Controller.class");
		}

	}
}
